﻿using Microsoft.SharePoint;
using AgileShare.Framework.Core;
using AgileShare.Framework.Library.Helpers;
using AgileShare.Framework.SiteProvisioning.Definitions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace AgileShare.Framework.SiteProvisioning.Helpers
{
	public static class FieldDefinitionHelper
	{
		/// <summary>
		/// Ensures the field.
		/// </summary>
		/// <param name="fieldDefinition">The field definition.</param>
		/// <param name="fieldCollection">The field collection.</param>
		/// <param name="updateIfExists">if set to <c>true</c> [update if exists].</param>
		/// <param name="pushChangesToList">if set to <c>true</c> [push changes to list].</param>
		public static void EnsureField(FieldDefinition fieldDefinition, SPFieldCollection fieldCollection, bool updateIfExists = false, bool pushChangesToList = false)
		{
			SPFieldHelper.EnsureField(fieldDefinition.DefinitionXml, fieldCollection, updateIfExists, pushChangesToList);
		}

		/// <summary>
		/// Ensures the fields.
		/// </summary>
		/// <param name="fieldDefinitions">The field definitions.</param>
		/// <param name="fieldCollection">The field collection.</param>
		/// <param name="updateIfExists">if set to <c>true</c> [update if exists].</param>
		/// <param name="pushChangesToLists">if set to <c>true</c> [push changes to lists].</param>
		public static void EnsureFields(IEnumerable<FieldDefinition> fieldDefinitions, SPFieldCollection fieldCollection, bool updateIfExists = false, bool pushChangesToLists = false)
		{
			foreach (FieldDefinition fieldDefinition in fieldDefinitions)
			{
				EnsureField(fieldDefinition, fieldCollection, updateIfExists, pushChangesToLists);
			}
		}

		private static T ChangeFieldType<T>(SPField field, FieldType fieldType, SPFieldCollection fieldCollection) where T : SPField
		{
			field.TypeAsString = fieldType.ToString();
			field.Update();

			var castedField = (T)fieldCollection[field.Id];
			return castedField;
		}

	}
}
